﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Security;
using LibMS.Filters;

namespace LibMS.Controllers
{
    [Authorize]
    public class ApiAuthenticationController : ApiController
    {
        private readonly LibMSMembershipProvider _membershipProvider = new LibMSMembershipProvider();

        [AllowAnonymous]
        [HttpPost]
        public HttpResponseMessage ValidateUser(string username, string password, bool rememberMe)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                var error = new
                {
                    success = false,
                    message = "Username or password is null, empty"
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            var result = _membershipProvider.ValidateUser(username, password);
            if (result)
            {
                FormsAuthentication.SetAuthCookie(username, rememberMe);
                var loginSuccess = new
                {
                    success = true,
                    isAuthenticated = true,
                    username = username
                };
                return Request.CreateResponse(HttpStatusCode.OK, loginSuccess);
            }
            else
            {
                if (!string.IsNullOrEmpty(_membershipProvider.ErrorMessage))
                {
                    var loginError = new
                    {
                        success = false,
                        message = _membershipProvider.ErrorMessage
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, loginError);
                }
                else
                {
                    var loginFail = new
                    {
                        success = true,
                        isAuthenticated = false
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, loginFail);
                }
            }
        }

        [HttpPost]
        public HttpResponseMessage Logout()
        {
            FormsAuthentication.SignOut();
            var logoutSuccess = new
            {
                success = true
            };
            return Request.CreateResponse(HttpStatusCode.OK, logoutSuccess);
        }
    }
}
